package com.stylefeng.guns.rest.modular.App.controller;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.util.CoodinateCovertor;
import com.stylefeng.guns.core.util.PingYinUtil;
import com.stylefeng.guns.rest.Tools.GlobalDefine;
import com.stylefeng.guns.rest.Util.*;
import com.stylefeng.guns.rest.modular.App.dao.LineTimeSlotMapper;
import com.stylefeng.guns.rest.modular.App.model.OrderLine;
import com.stylefeng.guns.rest.modular.App.service.IOrderLineService;
import com.stylefeng.guns.rest.Tools.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 线路基本信息
 *
 * @author 张亚林
 * @Date 2018-11-16 17:56
 */
@Controller
@RequestMapping(value = {"/gunsApi/auth/orderLine"})
@Api(value = "线路基本信息操作相关api", tags = {"线路基本信息操作接口"})
public class OrderLineController extends BaseController {
    @Autowired
    private IOrderLineService orderLineService;
    @Autowired
    private InitDefineCache initDefineCache;
    @Resource
    private LineTimeSlotMapper lineTimeSlotMapper;

    /**
     * 分页获取线路基本信息列表
     * @param orderLine
     * @param pageNum
     * @param pageSize
     * @return	
     */
    @ApiOperation(value = "分页获取线路基本信息列表", notes = "分页获取线路基本信息列表", httpMethod = "POST")
    @PostMapping(value = "/pageList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)	
    @ResponseBody
    public Result pageList(
        @RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine,
        @ApiParam(name = "pageNum", value = "当前页数", required = true) @RequestParam(value = "pageNum",defaultValue = "1", required = true) Integer pageNum,
        @ApiParam(name = "pageSize", value = "每页显示条数", required = true) @RequestParam(value = "pageSize",defaultValue = "1000",required = true) Integer pageSize,
        @ApiParam(name = "otCode", value = "线路类型", required = true) @RequestParam(value = "otCode", defaultValue = "CJ",required = true) String otCode
        ) {
        try {
            Map map=new HashMap();
            Pager pager=new Pager();
            pager.setPageNumber(pageNum);//页码从1 开始
            pager.setPageSize(pageSize);
            pager.setObj(orderLine);
            if(StringUtils.equals("CJ",otCode));
                map=orderLineService.pageListOrderLine(pager,getToken());
            return Result.success(map);
        }catch(Exception e){
            return Result.error(e.getMessage(),500100);
        }
    }
    /**
     * 获取线路基本信息列表
     * @param orderLine    
     * @return	
     */
    @ApiOperation(value = "获取线路基本信息列表", notes = "获取线路基本信息列表", httpMethod = "POST")
    @PostMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result list(
        @RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine,
        @ApiParam(name = "otCode", value = "线路类型", required = true) @RequestParam(value = "otCode", defaultValue = "CJ",required = true) String otCode) {
        try {
            Map map=new HashMap();
            if(StringUtils.equals("CJ",otCode))
                map=(Map) orderLineService.selectListOrderLine(orderLine,getToken());
            return Result.success(map);
        }catch(Exception e){
            return Result.error(e.getMessage(),500100);
        }
    }
    /**
     * 通过主键获取线路基本信息对象
     * @param id
     * @return
     */
    @ApiOperation(value = "通过主键获取线路基本信息对象", notes = "通过主键获取线路基本信息对象", httpMethod = "GET")
    @GetMapping(value = "/getById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getById(
            @ApiParam(name = "id", value = "主键ID", required = true) @RequestParam(value = "id", required = true) String  id
    ) {
        try {
            return Result.success( orderLineService.findOrderLineById(id,getToken()));
        }catch(Exception e){
            return Result.error(e.getMessage(),500100);
        }
    }
    /**
     * 刷新系统线路缓存
     * @param flg
     * @return
     */
    @ApiOperation(value = "刷新系统线路缓存", notes = "刷新系统线路缓存", httpMethod = "POST")
    @PostMapping(value = "/refreshCache", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result refreshCache(
            @ApiParam(name = "flg", value = "刷新标识", required = true) @RequestParam(value = "flg", required = true) String  flg
    ) {
        try {
            if(flg==null || !(java.net.URLDecoder.decode(flg,"utf-8").equals("kmcw2018@tty-backMag"))){
                return Result.error("缺少有效标识");
            }
            initDefineCache.init();
            return Result.success();
        }catch(Exception e){
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检测坐标点是否在城市区域内
     * @param lineId  线路Id
     * @param pos 经纬度
     * @param cityFlg 城市表示（S:起点，E:终点）
     * @return
     */
    @ApiOperation(value = "检测坐标点是否在城市区域内", notes = "检测坐标点是否在城市区域内", httpMethod = "POST")
    @PostMapping(value = "/checkPointInCity", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result checkPointInCity(
            @ApiParam(name = "lineId", value = "线路ID", required = true) @RequestParam(value = "lineId", required = true) String  lineId,
            @ApiParam(name = "pos", value = "起点经纬度", required = true) @RequestParam(value = "pos", required = true) String  pos,
            @ApiParam(name = "cityFlg", value = "城市表示（S:起点，E:终点）", required = true) @RequestParam(value = "cityFlg", required = true) String  cityFlg
    ) {

        if(lineId==null || lineId.length()<10 || pos==null || pos.length()<5 ||  !(cityFlg.equals("S") || cityFlg.equals("E"))){
            return Result.error("参数不全");
        }
        try {
            pos=java.net.URLDecoder.decode(pos,"utf-8");
            double lng=-1;
            double lat=-1;
            String[] points=pos.split(",");
            if(points.length!=2){
                return Result.error("经纬度坐标不正确");
            }else {
                try{
                    lng=Double.parseDouble(points[0]);
                    lat=Double.parseDouble(points[1]);
                }catch(Exception e){
                    return Result.error("经纬度坐标不正确");
                }
            }
            List<LineInf> listLine=CacheKit.get(GlobalDefine.DEFINEDEHCACHE,GlobalDefine.LINECACHE);
            LineInf inf=null;
            for(LineInf lineInf:listLine){
                if(lineInf.getOlId().equals(lineId)){
                    inf=lineInf;
                }
            }
            if(inf==null){
                return Result.error("未找到线路信息");
            }
            String cityId="";
            if(cityFlg.equals("S")){
                cityId=inf.getOlStartCityId();
            }else{
                cityId=inf.getOlEndCityId();
            }
            if(cityId==null || cityId.length()<10){
                return Result.error("线路城市坐标为设置，请设置后刷新缓存！");
            }
            Map<String,String > mapResult=new HashMap<>();
            if(initDefineCache.checkPoint(lng,lat,inf,cityId).length()>10){
                mapResult.put("exists","1");
            }else{
                mapResult.put("exists","0");
            }
            return Result.success(mapResult);
        }catch(Exception e){
            return Result.error(e.getMessage());
        }
    }
    /**
     * 获取线路城市
     * @param cityId
     * @return
     */
    @ApiOperation(value = "获取线路城市", notes = "获取线路城市", httpMethod = "POST")
    @PostMapping(value = "/getLineCity", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getLineCity(
            @ApiParam(name = "cityId", value = "起点城市Id", required = false) @RequestParam(value = "cityId", required = false) String  cityId
    ) {
        try {
            List<LineInf> listLine=CacheKit.get(GlobalDefine.DEFINEDEHCACHE,GlobalDefine.LINECACHE);
            Map<String,String> mapCityId=new HashMap<>();
            Map<String,List<CityInf>> mapCityInf=new TreeMap<>();
            boolean startCityFlg=false;
            if(cityId!=null && cityId.length()>10 ){
                startCityFlg=true;
            }
            for(LineInf lineInf:listLine){
                String city="";
                String cityName="";
                if(startCityFlg){
                    if(!cityId.equals(lineInf.getOlStartCityId())){
                        continue;
                    }
                    city=lineInf.getOlEndCityId();
                    cityName=lineInf.getOlEndCity();
                }else {
                    city=lineInf.getOlStartCityId();
                    cityName=lineInf.getOlStartCity();
                }
                String pyAll=PingYinUtil.getPinyin(cityName);
                String pyHead=PingYinUtil.getPinYinHeadChar(cityName);
                String pyFirst=pyHead.substring(0,1);
                if(mapCityId.containsKey(city)){
                    continue;
                }
                mapCityId.put(city,city);
                if(!mapCityInf.containsKey(pyFirst)){
                    mapCityInf.put(pyFirst,new ArrayList<CityInf>());
                }
                List<CityInf> listCityInf=mapCityInf.get(pyFirst);
                CityInf cityInf=new CityInf();
                cityInf.setCityId(city);
                cityInf.setCityName(cityName);
                cityInf.setPyAll(pyAll);
                cityInf.setPyFirst(pyFirst);
                cityInf.setPyHead(pyHead);
                listCityInf.add(cityInf);
            }
            //List<CityInf> listCityInf=new ArrayList();
            Iterator<String> it=mapCityInf.keySet().iterator();
            List<CityInfArry> listData=new ArrayList<>();
            while(it.hasNext()){
                String key=it.next();
                CityInfArry cityInfArry=new CityInfArry();
                cityInfArry.setIndex(key);
                cityInfArry.getData().addAll(mapCityInf.get(key));
                listData.add(cityInfArry);
                //listCityInf.addAll(mapCityInf.get(key));
            }
            return Result.success(listData);
        }catch(Exception e){
            return Result.error("服务端异常!",500100);
        }
    }
    /**
     * 根据起点城市和终点城市获取线路从缓存
     * @param scityId
     * @param ecityId
     * @return
     */
    @ApiOperation(value = "根据起点城市和终点城市获取线路从缓存", notes = "根据起点城市和终点城市获取线路从缓存", httpMethod = "POST")
    @PostMapping(value = "/getLineFromCacheByCity", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getLineFromCacheByCity(
            @ApiParam(name = "scityId", value = "起点城市id", required = true) @RequestParam(value = "scityId", required = false) String  scityId,
            @ApiParam(name = "ecityId", value = "终点城市id", required = true) @RequestParam(value = "ecityId", required = false)  String  ecityId
    ) {

        try {
            LineInf line_inf=new LineInf();
            List<LineInf> listLine=CacheKit.get(GlobalDefine.DEFINEDEHCACHE,GlobalDefine.LINECACHE);
            for(LineInf lineInf:listLine){
                if(scityId.equals(lineInf.getOlStartCityId()) && ecityId.equals(lineInf.getOlEndCityId())){
                    line_inf=lineInf;
                    break;
                }
            }
            return Result.success(line_inf);
        }catch(Exception e){
            return Result.error("服务端异常!",500100);
        }
    }
    /**
     * 获取线路从缓存
     * @param lineId
     * @param lineName
     * @return
     */
    @ApiOperation(value = "获取线路从缓存", notes = "获取线路从缓存", httpMethod = "POST")
    @PostMapping(value = "/getLineFromCache", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getLineFromCache(
            @ApiParam(name = "lineId", value = "线路ID", required = false) @RequestParam(value = "lineId", required = false) String  lineId,
            @ApiParam(name = "lineName", value = "线路名称", required = false) @RequestParam(value = "lineName", required = false)  String  lineName
    ) {

        try {

            List<LineInf> listLine=CacheKit.get(GlobalDefine.DEFINEDEHCACHE,GlobalDefine.LINECACHE);
            if((lineId==null || lineId.length()<10 ) && (lineName==null || lineName.trim().length()<2)){
                return Result.success(listLine);
            }else if(lineId!=null && lineId.length()>10){
                for(LineInf lineInf:listLine){
                    if(lineInf.getOlId().equals(lineId)){
                        List<LineInf> list=new ArrayList<LineInf>();
                        list.add(lineInf);
                        return Result.success(list);
                    }
                }
            }else{
                lineName =java.net.URLDecoder.decode(lineName,"utf-8");
                lineName=lineName.replace("—","-");
                for(LineInf lineInf:listLine){
                    if(lineInf.getOlName().replace("—","-").contains(lineName)){
                        List<LineInf> list=new ArrayList<LineInf>();
                        list.add(lineInf);
                        return Result.success(list);
                    }
                }
            }
        }catch(Exception e){
            return Result.error("服务端异常!",500100);
        }
        return Result.success(new ArrayList());
    }
    @ApiOperation(value = "获取线路价格和里程", notes = "获取线路价格和里程", httpMethod = "POST")
    @PostMapping(value = "/getPriceKmFromCache", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getPriceKmFromCache(
            @ApiParam(name = "lineId", value = "线路ID", required = true) @RequestParam(value = "lineId", required = true) String  lineId,
            @ApiParam(name = "startpos", value = "起点经纬度", required = true) @RequestParam(value = "startpos", required = true) String  startpos,
            @ApiParam(name = "endpos", value = "终点经纬度", required = true) @RequestParam(value = "endpos", required = true) String  endpos,
            @ApiParam(name = "sendTime", value = "预约时间（yyyy-MM-dd HH:mm）", required = true) @RequestParam(value = "sendTime", required = true) String sendTime
    ) {
        if(lineId==null || lineId.length()<10 || startpos==null || startpos.length()<5 || endpos==null || endpos.length()<5 || sendTime==null || sendTime.length()<16  ){
            return Result.error("参数不全");
        }
        try {
            //System.out.println("开始获取线路价格及里程");
            startpos=java.net.URLDecoder.decode(startpos,"utf-8");
            endpos=java.net.URLDecoder.decode(endpos,"utf-8");
            sendTime=java.net.URLDecoder.decode(sendTime,"utf-8");
            //System.out.println("接受参数：s:["+startpos+"]e:["+endpos+"]sendTime:["+sendTime+"]lineId:["+lineId+"]");
            double slng=-1;
            double slat=-1;
            double elgn=-1;
            double elat=-1;
            String[] points=startpos.split(",");
            if(points.length!=2){
                return Result.error("出发地坐标不正确");
            }else {
                try{
                    slng=Double.parseDouble(points[0]);
                    slat=Double.parseDouble(points[1]);
                }catch(Exception e){
                    return Result.error("出发地坐标不正确");
                }
            }
            points=endpos.split(",");
            if(points.length!=2){
                return Result.error("目的地坐标不正确");
            }else {
                try{
                    elgn=Double.parseDouble(points[0]);
                    elat=Double.parseDouble(points[1]);
                }catch(Exception e){
                    return Result.error("目的地坐标不正确");
                }
            }

            List<LineInf> listLine=CacheKit.get(GlobalDefine.DEFINEDEHCACHE,GlobalDefine.LINECACHE);
            LineInf inf=null;
            for(LineInf lineInf:listLine){
                if(lineInf.getOlId().equals(lineId)){
                    inf=lineInf;
                }
            }
            if(inf==null){
                return Result.error("未找到线路信息");
            }
            Map<String,Object> mapResult=new HashMap<>();
            String sCityId=inf.getOlStartCityId();
            String eCityId=inf.getOlEndCityId();
            BigDecimal sbd=initDefineCache.getCityZonePriceByPoint(slng, slat,inf,sCityId);
            BigDecimal ebd=initDefineCache.getCityZonePriceByPoint(elgn, elat,inf,eCityId);
            if(sbd.compareTo(new BigDecimal(0))<0){
                sbd=new BigDecimal(0);
            }
            if(ebd.compareTo(new BigDecimal(0))<0){
                ebd=new BigDecimal(0);
            }
            String sdate=sendTime;
            //根据经纬度坐标 获取两点距离
            String km=CoodinateCovertor.getDistanceByPoint(startpos,endpos);
            String kmPrice=initDefineCache.getKmPrice(inf,Float.parseFloat(km));
            String datePrice=initDefineCache.getDatePrice(inf,sdate.substring(0,10));
            String timePrice="0.00";
            timePrice=initDefineCache.getTimePrice(inf,sdate.substring(11).trim());

            mapResult.put("sprice",sbd);
            mapResult.put("eprice",ebd);
            mapResult.put("timePrice", timePrice);
            mapResult.put("datePrice", datePrice);
            mapResult.put("kmPrice", kmPrice);
            mapResult.put("km", km);
            return Result.success(mapResult);
        }catch(Exception e){
            return Result.error(e.getMessage());
        }
    }
    /**
     * 获取线路基本信息的Key-Value列表，用于html的Select数据源
     * @param orderLine
     * @return
     */
    @ApiOperation(value = "获取线路基本信息的Key-Value列表，用于html的Select数据源", notes = "获取线路基本信息的Key-Value列表，用于html的Select数据源", httpMethod = "POST")
    @PostMapping(value = "/optionsList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result optionsList(@RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine) {
        try {
            return Result.success(orderLineService.optionsOrderLine(orderLine,getToken()));
        }catch(Exception e){
            return Result.error(e.getMessage(),500100);
        }
    }
    /**
     * 获取线路基本信息列表
     * @param lineId
     * @param sendDate
     * @return
     */
    @ApiOperation(value = "获取线路排班列表", notes = "获取线路排班列表", httpMethod = "GET")
    @GetMapping(value = "/listSchedule", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result listSchedule(
            @ApiParam(name = "lineId", value = "线路ID", required = true) @RequestParam(value = "lineId", required = true) String  lineId,
            @ApiParam(name = "sendDate", value = "出发日期", required = true) @RequestParam(value = "sendDate", required = true) String  sendDate) {
        try {
            LineTimeSlot lineTimeSlot = new LineTimeSlot();
            lineTimeSlot.setOlId(lineId);
            lineTimeSlot.setLtsDate(new SimpleDateFormat("yyyy-MM-dd").parse(sendDate));
            return Result.success(lineTimeSlotMapper.selectListLineTimeSlotForCache(lineTimeSlot));
        }catch(Exception e){
            return Result.error(e.getMessage(),500100);
        }
    }
	private String getToken(){		
		return getHttpServletRequest().getHeader("Authorization").substring(7);
    }
}
